package com.chy.srb.sms.controller.api;

import com.chy.srb.common.exception.Assert;
import com.chy.srb.common.result.R;
import com.chy.srb.common.result.ResponseEnum;
import com.chy.srb.common.util.RandomUtils;
import com.chy.srb.common.util.RegexValidateUtils;
import com.chy.srb.sms.service.SmsService;
import com.chy.srb.sms.util.SmsProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @Author: chenhy
 * @Date: 2022年01月21日
 */
@Api(tags = "短信管理")
@Slf4j
@RestController
@RequestMapping("/api/sms")
@CrossOrigin // 跨域
public class ApiSmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

//    @Autowired
//    private CoreUserInfoClient coreUserInfoClient;

    @ApiOperation("获取验证码")
    @GetMapping("/send/{mobile}")
    public R send(@ApiParam(value = "手机号", required = true) @PathVariable String mobile) throws Exception {
        // 校验手机号吗不能为空
        Assert.notEmpty(mobile, ResponseEnum.MOBILE_NULL_ERROR);
        // 是否是合法的手机号码
        Assert.isTrue(RegexValidateUtils.checkCellphone(mobile), ResponseEnum.MOBILE_ERROR);

        // 判断手机号是否已经注册
//        boolean result = coreUserInfoClient.checkMobile(mobile);
//        log.info("result = " + result);
//        Assert.isTrue(!result, ResponseEnum.MOBILE_EXIST_ERROR);

        String code = RandomUtils.getFourBitRandom();
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", code);
        smsService.send(mobile, SmsProperties.TEMPLATE_CODE, map);

        // 将验证码存入redis
        redisTemplate.opsForValue().set("srb:sms:code:" + mobile, code, 5, TimeUnit.MINUTES);

        return R.ok().message("短信发送成功");
    }
}
